package com.itheima.tlias84.Service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias84.Po.InsertEmpParam;
import com.itheima.tlias84.Po.SelectEmpPageParam;
import com.itheima.tlias84.Po.UpdateEmpParam;
import com.itheima.tlias84.Service.EmpService;
import com.itheima.tlias84.Util.ResultUtil;
import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.dto.ReportEmpGenderDTO;
import com.itheima.tlias84.dto.SelectEmpDTO;
import com.itheima.tlias84.entity.Expr;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.mapper.ExprMapper;
import com.itheima.tlias84.vo.PageVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Resource
    EmpMapper empMapper;
    @Resource
    ExprMapper exprMapper;

    @Override
    public ResultUtil selectEmpByPage(SelectEmpPageParam param) {
        // param.setPage((param.getPage()-1)*param.getPageSize());
        //注意pageHelper会自动执行一个count sql,并且会自动拼接上limit
        //因此必须写在自己的sql之前
        Page<Object> page = PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SelectEmpDTO> dtos = empMapper.selectEmpByPage(param);
        PageVO<SelectEmpDTO> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        //pageVO.setTotal(dtos.size());
        pageVO.setRows(dtos);
        return ResultUtil.success(pageVO);
    }

    @Log
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int batchDelete(List<Integer> ids) {
        //先删除员工
        int i = empMapper.batchDelete(ids);
        //再删除员工履历
        int i1 = exprMapper.batchDeleteExpr(ids);
        log.info("删除{}条履历", i1);

        return i;
    }
    @Log
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertEmp(InsertEmpParam param) {
        //设置时间
        param.setCreateTime(LocalDateTime.now());
        param.setUpdateTime(LocalDateTime.now());
        int flag = empMapper.insertEmp(param);
        //插入工作履历
        log.info("员工回显的主键{}", param.getId());
        List<Expr> exprList = param.getExprList();
        if (CollectionUtils.isNotEmpty(exprList)) {
            // if (Objects.nonNull(param.getExprList()) && !param.getExprList().isEmpty()) {
            //赋值员工id以及时间
            // List<Expr> exprList = param.getExprList();
            exprList = exprList.stream().map(t -> {
                t.setEmpId(param.getId());
                t.setCreateTime(LocalDateTime.now());
                t.setUpdateTime(LocalDateTime.now());
                return t;
            }).toList();
            int i = exprMapper.batchInsertExpr(exprList);
            log.info("插入工作履历{}", i);

        }
        return flag;
    }

    @Override
    public SelectEmpDTO selectEmpById(Integer id) {
        //先查询员工
        SelectEmpDTO dto = empMapper.selectEmpById(id);
        //在查询履历
        List<Expr> exprs = exprMapper.selectExprByEmpId(id);
        dto.setExprList(exprs);
        return dto;
    }

    @Log
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateEmp(UpdateEmpParam param) {
        param.setUpdateTime(LocalDateTime.now());
        //1.先更新员工表信息
        int empRows = empMapper.updateEmp(param);

        //2.再删除员工所有履历
        int exprDelRows = exprMapper.batchDeleteExpr(List.of(param.getId()));
        log.info("删除{}条旧履历", exprDelRows);

        //3.再新增履历
        List<Expr> exprList = param.getExprList();
        if (CollectionUtils.isNotEmpty(exprList)) {
            //赋值员工id以及时间7
            exprList = exprList.stream().map(t -> {
                t.setEmpId(param.getId());
                t.setCreateTime(LocalDateTime.now());
                t.setUpdateTime(LocalDateTime.now());
                return t;
            }).toList();
            int i = exprMapper.batchInsertExpr(exprList);
            log.info("插入{}条新工作履历", i);

        }
        return empRows;
    }

    /**
     * 员工性别统计
     * @return
     */
    @Override
    public List<ReportEmpGenderDTO> countEmpByGender() {
        return empMapper.countEmpByGender();
    }

    @Override
    public ResultUtil countEmpJob() {
        List<Integer> jobs = empMapper.countEmpJob();
        Map<String, List<Integer>> map = jobs.stream().collect(Collectors.groupingBy(t -> {
            //写相应的职位
            return switch (t) {
                //
                case 1 -> "班主任";
                case 2 -> "讲师";
                case 3 -> "学工主管";
                case 4 -> "教研主管";
                case 5 -> "咨询师";
                default -> "其他";
            };
        }));
        Set<String> jobList = map.keySet();
        List<Integer> dataList = map.values().stream().map((t)-> t.size()).toList();
//        //再建一个DTO来存储(往后不用了)or建一个map存储
//        HashMap<Object, Object> resultMap = new HashMap<>();
//        resultMap.put("jobList", jobList);
//        resultMap.put("dataList", dataList);
//        //优化-->专门构建Json对象/Json数组的jar
        JSONObject jsonObject = new JSONObject();
        //操作与map相似,但不用指定泛型
        jsonObject.put("jobList", jobList);
        jsonObject.put("dataList", dataList);
        return ResultUtil.success(jsonObject);


    }

    @Override
    public List<SelectEmpDTO> selectAll() {
        return empMapper.selectAll();
    }

}